package logic

import (
	"context"
	"fmt"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"
	"go-zero-mall/app/admin/model"
	"go-zero-mall/common/tool"
	"go-zero-mall/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AdminLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAdminLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminLoginLogic {
	return &AdminLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理员-用户登录
func (l *AdminLoginLogic) AdminLogin(in *pd.AdminLoginReq) (*pd.AdminLoginResp, error) {
	var userId int64
	var err error
	userId, err = l.loginByUserName(in)
	if err != nil {
		return nil, err
	}
	getJwtToken := NewGenerateTokenLogic(l.ctx, l.svcCtx)
	tokenResp, err := getJwtToken.GenerateToken(&pd.GenerateTokenReq{UserId: userId})
	if err != nil {
		return nil, errors.Wrapf(ErrGenerateTokenError, "GenerateToken userId : %d", userId)
	}

	return &pd.AdminLoginResp{Token: tokenResp.AccessToken, TokenHead: tokenResp.AccessToken}, nil
}

func (l *AdminLoginLogic) loginByUserName(in *pd.AdminLoginReq) (int64, error) {
	user, err := l.svcCtx.UmsAdminModel.FindOneByName(l.ctx, in.Username)
	if err != nil && err != model.ErrNotFound {
		return 0, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "根据用户名查询用户信息失败，mobile:%s,err:%v", in.Username, err)
	}
	if user == nil {
		return 0, errors.Wrapf(xerr.NewErrMsg("用户不存在"), "username:%s", in.Username)
	}
	fmt.Println(tool.Md5ByString(in.Password))
	if tool.Md5ByString(in.Password) != user.Password {
		return 0, errors.New("密码不正确")
	}
	return user.Id, nil
}
